<template>
  <div class="order-shipping page-container">
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">订单发货</h1>
        <p class="page-subtitle">批量处理订单发货，支持物流信息导入</p>
      </div>
    </div>

    <div class="content-card">
      <!-- 操作区域 -->
      <div class="operation-section">
        <div class="template-section">
          <div class="template-card">
            <div class="template-icon">
              <svg viewBox="0 0 24 24" fill="currentColor" class="icon">
                <path
                  d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"
                />
              </svg>
            </div>
            <div class="template-content">
              <h3 class="template-title">下载导入模板</h3>
              <p class="template-desc">
                下载标准格式的Excel模板，按照模板格式填写物流信息
              </p>
              <el-button
                type="primary"
                size="large"
                @click="downloadTemplate"
                :loading="downloadLoading"
                class="download-btn"
              >
                <el-icon class="btn-icon">
                  <Download />
                </el-icon>
                下载模板
              </el-button>
            </div>
          </div>
        </div>

        <div class="upload-section">
          <div class="upload-card">
            <div class="upload-icon">
              <svg viewBox="0 0 24 24" fill="currentColor" class="icon">
                <path
                  d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"
                />
              </svg>
            </div>
            <div class="upload-content">
              <h3 class="upload-title">上传物流信息</h3>
              <p class="upload-desc">
                上传已填写完成的Excel文件，系统将自动解析并处理
              </p>

              <el-upload
                ref="uploadRef"
                class="upload-dragger"
                drag
                :action="uploadUrl"
                :headers="uploadHeaders"
                :data="uploadData"
                :before-upload="beforeUpload"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
                :on-progress="handleUploadProgress"
                :file-list="fileList"
                :auto-upload="false"
                accept=".xlsx,.xls"
                :limit="1"
              >
                <div class="upload-area">
                  <div class="upload-icon-large">
                    <svg
                      viewBox="0 0 24 24"
                      fill="currentColor"
                      class="upload-svg"
                    >
                      <path
                        d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"
                      />
                    </svg>
                  </div>
                  <div class="upload-text">
                    <p class="upload-main-text">点击或拖拽文件到此区域上传</p>
                    <p class="upload-sub-text">
                      支持 .xlsx 和 .xls 格式，文件大小不超过 10MB
                    </p>
                  </div>
                </div>
              </el-upload>

              <div class="upload-actions">
                <el-button
                  type="success"
                  size="large"
                  @click="submitUpload"
                  :loading="uploadLoading"
                  :disabled="fileList.length === 0"
                  class="submit-btn"
                >
                  <el-icon class="btn-icon">
                    <Upload />
                  </el-icon>
                  开始处理
                </el-button>
                <el-button
                  size="large"
                  @click="clearFiles"
                  :disabled="fileList.length === 0"
                  class="clear-btn"
                >
                  <el-icon class="btn-icon">
                    <Delete />
                  </el-icon>
                  清空文件
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 处理结果 -->
      <div v-if="processResult" class="result-section">
        <div class="result-card">
          <div class="result-header">
            <h3 class="result-title">处理结果</h3>
            <el-tag
              :type="processResult.success ? 'success' : 'danger'"
              size="large"
            >
              {{ processResult.success ? "处理成功" : "处理失败" }}
            </el-tag>
          </div>
          <div class="result-content">
            <div class="result-stats">
              <div class="stat-item">
                <span class="stat-label">总记录数:</span>
                <span class="stat-value">{{ processResult.total || 0 }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">成功数:</span>
                <span class="stat-value success">{{
                  processResult.successCount || 0
                }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">失败数:</span>
                <span class="stat-value error">{{
                  processResult.failCount || 0
                }}</span>
              </div>
            </div>
            <div v-if="processResult.message" class="result-message">
              <p>{{ processResult.message }}</p>
            </div>
            <div
              v-if="processResult.errors && processResult.errors.length"
              class="error-details"
            >
              <h4>错误详情:</h4>
              <ul>
                <li v-for="(error, index) in processResult.errors" :key="index">
                  {{ error }}
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { Download, Upload, Delete } from "@element-plus/icons-vue";

// 类型定义
interface ProcessResult {
  success: boolean;
  total?: number;
  successCount?: number;
  failCount?: number;
  message?: string;
  errors?: string[];
}

const uploadRef = ref();
const fileList = ref([]);
const downloadLoading = ref(false);
const uploadLoading = ref(false);
const processResult = ref<ProcessResult | null>(null);

// 上传配置
const uploadUrl = "/api/internal/order/uploadShipping";
const uploadHeaders = {
  Authorization: `Bearer ${localStorage.getItem("token")}`,
};
const uploadData = {};

// 下载模板
const downloadTemplate = async () => {
  downloadLoading.value = true;
  try {
    // 创建下载链接
    const link = document.createElement("a");
    link.href = "/template/订单发货物流导入模版.xlsx";
    link.download = "订单发货物流导入模版.xlsx";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    ElMessage.success("模板下载成功");
  } catch (error) {
    console.error("下载模板失败:", error);
    ElMessage.error("下载模板失败");
  } finally {
    downloadLoading.value = false;
  }
};

// 上传前检查
const beforeUpload = (file: File) => {
  const isExcel =
    file.type ===
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
    file.type === "application/vnd.ms-excel";
  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isExcel) {
    ElMessage.error("只能上传 Excel 文件!");
    return false;
  }
  if (!isLt10M) {
    ElMessage.error("文件大小不能超过 10MB!");
    return false;
  }
  return true;
};

// 上传成功
const handleUploadSuccess = (response: any) => {
  uploadLoading.value = false;
  if (response.code === 0) {
    processResult.value = response.data;
    ElMessage.success("文件上传并处理成功");
  } else {
    ElMessage.error(response.message || "处理失败");
    processResult.value = {
      success: false,
      message: response.message || "处理失败",
    };
  }
};

// 上传失败
const handleUploadError = (error: any) => {
  uploadLoading.value = false;
  console.error("上传失败:", error);
  ElMessage.error("上传失败");
  processResult.value = {
    success: false,
    message: "上传失败",
  };
};

// 上传进度
const handleUploadProgress = (event: any) => {
  console.log("上传进度:", event.percent);
};

// 提交上传
const submitUpload = () => {
  if (fileList.value.length === 0) {
    ElMessage.warning("请先选择文件");
    return;
  }

  uploadLoading.value = true;
  uploadRef.value.submit();
};

// 清空文件
const clearFiles = () => {
  uploadRef.value.clearFiles();
  processResult.value = null;
};
</script>

<style scoped>
.order-shipping {
  padding: 20px;
  min-height: 100vh;
  background: #f8fafc;
}

.page-header {
  margin-bottom: 30px;
  text-align: center;
}

.header-content h1 {
  margin: 0 0 12px 0;
  font-size: 32px;
  font-weight: 700;
  color: #1a202c;
}

.header-content p {
  margin: 0;
  color: #718096;
  font-size: 16px;
  font-weight: 400;
}

.content-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.operation-section {
  padding: 40px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
}

.template-section,
.upload-section {
  display: flex;
  flex-direction: column;
}

.template-card,
.upload-card {
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border-radius: 12px;
  padding: 30px;
  text-align: center;
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.template-card:hover,
.upload-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.08);
}

.template-icon,
.upload-icon {
  width: 60px;
  height: 60px;
  margin: 0 auto 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.icon {
  width: 30px;
  height: 30px;
}

.template-title,
.upload-title {
  margin: 0 0 12px 0;
  font-size: 20px;
  font-weight: 600;
  color: #1a202c;
}

.template-desc,
.upload-desc {
  margin: 0 0 24px 0;
  color: #718096;
  font-size: 14px;
  line-height: 1.5;
}

.download-btn,
.submit-btn,
.clear-btn {
  padding: 12px 24px;
  font-size: 14px;
  font-weight: 600;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.download-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
}

.download-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 12px rgba(102, 126, 234, 0.3);
}

.btn-icon {
  margin-right: 6px;
}

.upload-dragger {
  width: 100%;
  margin-bottom: 20px;
}

.upload-area {
  padding: 30px;
  text-align: center;
}

.upload-icon-large {
  width: 48px;
  height: 48px;
  margin: 0 auto 20px;
  color: #a0aec0;
}

.upload-svg {
  width: 100%;
  height: 100%;
}

.upload-main-text {
  margin: 0 0 6px 0;
  font-size: 16px;
  font-weight: 600;
  color: #2d3748;
}

.upload-sub-text {
  margin: 0;
  font-size: 12px;
  color: #718096;
}

.upload-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.submit-btn {
  background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
  border: none;
  color: white;
}

.submit-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 12px rgba(72, 187, 120, 0.3);
}

.clear-btn {
  background: #f7fafc;
  border: 1px solid #e2e8f0;
  color: #4a5568;
}

.clear-btn:hover {
  background: #edf2f7;
  transform: translateY(-1px);
}

.result-section {
  padding: 30px 40px;
  border-top: 1px solid #e2e8f0;
  background: #f8fafc;
}

.result-card {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e2e8f0;
}

.result-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #2d3748;
}

.result-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.result-stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.stat-item {
  text-align: center;
  padding: 16px;
  background: #f8fafc;
  border-radius: 6px;
}

.stat-label {
  display: block;
  font-size: 12px;
  color: #718096;
  margin-bottom: 6px;
}

.stat-value {
  display: block;
  font-size: 20px;
  font-weight: 700;
  color: #2d3748;
}

.stat-value.success {
  color: #48bb78;
}

.stat-value.error {
  color: #f56565;
}

.result-message {
  padding: 12px;
  background: #edf2f7;
  border-radius: 6px;
  color: #4a5568;
  font-size: 14px;
}

.error-details {
  padding: 12px;
  background: #fed7d7;
  border-radius: 6px;
  color: #c53030;
  font-size: 14px;
}

.error-details h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  font-weight: 600;
}

.error-details ul {
  margin: 0;
  padding-left: 16px;
}

.error-details li {
  margin-bottom: 2px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .operation-section {
    grid-template-columns: 1fr;
    padding: 20px;
    gap: 20px;
  }

  .template-card,
  .upload-card {
    padding: 20px;
  }

  .result-section {
    padding: 20px;
  }

  .result-stats {
    grid-template-columns: 1fr;
  }

  .upload-actions {
    flex-direction: column;
  }

  .header-content h1 {
    font-size: 24px;
  }
}
</style>
